<template>
  <el-card class="box-card">
    <el-row slot="header" class="clearfix">
      <el-col :span="18">
        <span>平台余额</span>
      </el-col>
      <el-col :span="6" style="text-align: right">
        <el-button v-if="roleCheck('sync-balance')" size="mini" type="primary" @click="syncBalance">同步余额</el-button>
      </el-col>
    </el-row>
    <div v-loading="loading">
      <el-table :data="gameBalance">
        <el-table-column v-for="item in balanceList" :label="item.title" prop="value" :key="item.value+'gameBalance'">
          <template slot-scope="{row}">
            {{row[item.value] | currency}}
          </template>
        </el-table-column>
      </el-table>
      <!--新增第三方账户名-->
      <el-table class="el-table-no-head " :data="gameUserName">
        <el-table-column v-for="item in balanceList" :key="item.value+'gameUserName'">
          <template slot-scope="{row,column,$index}">
            {{item.value===0?'第三方账户名':row[item.value]}}
          </template>
        </el-table-column>
      </el-table>
      <el-table v-if="roleCheck('recycle-transfer') && gameBalance" :data="gameBalance" class="el-table-no-head ">
        <el-table-column v-for="item in balanceList" :key="item.value+'open'">
          <template slot-scope="{row,column,$index}">
            <el-button @click="item.value===0?transferInto(0):openDialog(item.value)" type="text">
              {{item.value===0?'一键回收平台余额':(item.value!==101?'转入':'')}}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog :modal="true" append-to-body :inline="true" title="从中心钱包转入" v-if="dialogVisible"
               :visible.sync="dialogVisible">
      <el-form :model="form" :rules="refRule" ref="refForm">
        <el-form-item  prop="amount">
          <p slot="label" style="display: inline-block;padding: 0px;margin: 0px;">
            <span>转入金额</span>
            <span v-if="form.channelId===23" style="color:#ff4747">（mw捕鱼不支持转入小数）</span>
          </p>
          <el-input
            v-model="form.amount"
            maxlength="9"
            auto-complete="off"
            @keyup.native="checkInput"
          >
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="transferInto(form.channelId)">确 定</el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import {
  getMemberBalance,
  memberBalanceTransfer,
  memberBalanceRecover,
  syncMemberBalance,
} from '@/services/api/member';

import { grid, factory, form } from '@/build';

export default {
  name: 'platform-balance',
  props: ['id'],
  mixins: [grid, factory, form],
  data() {
    return {
      platformBalance: [],
      balanceArr: [],
      balanceList: _.cloneDeep(consts.TRANSFER_PLATFORMS.filter(item => item.title != '虚拟体育')),
      loading: false,
      dialogVisible: false,
      form: {
        userId: this.$store.state.member.member_id,
        channelId: undefined,
        amount: undefined,
      },
      refRule: {
        amount:
            [
              {
                required: true,
                message: '金额必须填写',
              },
              { validator: factory.getValidator('nonNegativeNumber') },
            ],
      },
      countDownSeconds: 10,
      countDownFlag: 0,
      recycleCountDown: null,
      transferLimitFlag: false,
      transferLimitTimer: undefined,
    };
  },

  computed: {
    gameBalance() {
      const _data = {};
      _.map(this.balanceList, (item) => {
        _data[item.value] = item.balance;
      });
      return [_data];
    },
    gameUserName() {
      const _data = {};
      _.map(this.balanceList, (item) => {
        _data[item.value] = item.username;
      });
      return [_data];
    },
  },
  mounted() {
    _.each(this.balanceList, (item) => {
      if (item.title === '中心钱包') {
        item.title = '主账户余额';
      }
    });
    // const { member_id } = this.$store.state.member;

    this.bindGet(getMemberBalance, 'balanceArr', {
      action: 'getGrid',
      // sendingData: { userId: member_id },
      sendingData: { userId: this.id },
      format: (data) => {
        this.balanceList.forEach((v, k) => {
          data.forEach((_v, _k) => {
            if (v.value == _v.channelId) {
              v.balance = _v.balance;
              v.username = _v.username;
            }
          });
        });
        return data;
      },
    });
    this.bindSave(memberBalanceTransfer, 'saveForm', 'form', {
      // afterSuccess: () => {
      //   this.dialogVisible = false;
      //   this.resetForm('refForm');
      //   this.getAll();
      //   // this.form.from = ''
      // },
      callback: ([result, data]) => {
        this.resetForm('refForm');
        if (result) {
          this.$notify({
            title: '保存成功',
            type: 'success',
            duration: 2000,
          });
          this.dialogVisible = false;
          this.getAll();
        } else {
          this.$notify({
            title: `保存失败，${data.message}`,
            type: 'error',
            duration: 2000,
          });
        }
      },
    });
    this.getAll();

    // this.loading = true
    // (member_id).then(([result,data])=>{
    //   this.loading = false
    //   if(result){
    //     if(data.list && data.list.length>0){
    //       console.log(data)
    //       this.platformBalance = data.list
    //       this.balanceList = this.formatBalanceList(data.list)
    //     }
    //     // this.balanceList = data.list
    //   }
    // })
  },
  watch: {
    dialogVisible(newVal) {
      if (!newVal) {
        this.form.amount = undefined;
      }
    },
  },
  methods: {
    checkInput(e) {
      if (e.keyCode === 13) {
        this.transferInto(this.form.channelId);
        return;
      }
      if (this.form.channelId !== 23) {
        this.testNumber(this.form, 'amount');
      } else {
        this.testIntNumber(this.form, 'amount');
      }
    },
    testNumber(filters, key) { // 只允许输入最多包含两个小数点的数字
      filters[key] = filters[key].replace(/[^\d.]/g, ''); // 不允许输入数字和小数点以外的字符
      filters[key] = filters[key].replace(/^[0]+/, 0); // 数字开头最多只允许输入一个0
      if (/^[0]\d/.test(filters[key])) {
        filters[key] = filters[key].substr(1);
      }
      if (filters[key] && filters[key] === '.') { // 不能以小数点开头
        filters[key] = '';
      }
      if (filters[key].indexOf('.') !== filters[key].lastIndexOf('.')) { // 不允许输入两个小数点
        filters[key] = filters[key].substr(0, filters[key].length - 1);
      }
      if (filters[key].indexOf('.') > -1) { // 小数点后面只允许输入两位小数
        const arr = filters[key].split('.');
        const floatNumber = arr[1].length > 2 ? arr[1].substr(0, 2) : arr[1];
        filters[key] = `${arr[0]}.${floatNumber}`;
      }
    },
    testIntNumber(item, key) { // 只允许输入整数数字
      item[key] = item[key].replace(/[^\d]/g, '');
      const rexExStr = /^0\d/;
      if (rexExStr.test(item[key])) {
        item[key] = item[key].substr(1);
      }
    },
    transferInto(channelId) {
      this.form.channelId = channelId;
      // 回收
      if (channelId === 0) {
        this.recycleTimeDown();
        if (this.countDownFlag < 2 || this.countDownSeconds <= 0) {
          this.onRecycle().then((success) => {
            this.$message({ type: 'success', message: '回收成功' });
          }).catch((e)=> {
            this.$message({ type: 'error', message: '回收失败' });
          });
          this.countDownSeconds = 10;
        } else {
          this.$message({
            type: 'warning',
            message: '10s后再点击',
          });
        }
      } else if (!this.transferLimitFlag) {
        this.transferLimitFlag = true;
        this.transferLimitTimer = setTimeout(() => {
          this.transferLimitFlag = false;
          clearTimeout(this.transferLimitTimer);
        }, 1000);
        this.doSave({
          action: 'saveForm',
          form: 'refForm',
        });
      }
    },
    openDialog(toPlatform) {
      this.form.channelId = toPlatform;
      this.dialogVisible = true;
    },
    recycleTimeDown() {
      const self = this;
      this.countDownFlag++;
      this.recycleCountDown = setInterval(() => {
        self.countDownSeconds--;
        if (self.countDownSeconds < 0) {
          clearInterval(self.recycleCountDown);
        }
      }, 1000);
    },

    async onRecycle() {
      const promises = [];
      const result = [];
      this.balanceList.map((item) => {
        if (item.value === 0) return;
        if (item.balance && Number(item.balance) > 0) {
          promises.push(
            {
              userId: this.$store.state.member.member_id,
              channelId: item.value,
            },
          );
        }
      });
      for (const arg of promises) {
        try{
         await memberBalanceRecover(arg);
        }catch(e){
          this.$message({ type: 'error', message: e.message });
        }
      }
      await this.getAll();

      // Promise.all(promises).then(() => {
      //   this.getAll()
      // });
    },

    //
    syncBalance() {
      this.loading = true;
      const promises = [];
      this.balanceList.map((item) => {
        // if (item.balance && Number(item.balance) > 0) {
        promises.push(
          syncMemberBalance({
            // userId: this.$store.state.member.member_id,
            userId: this.id,
            channelId: item.value,
          }),
        );
        // }
      });
      Promise.all(promises)
        .then(() => {
          this.getAll();
        });
    },
  },
};
</script>

<style lang="scss">

  .el-table-no-head {
    .el-table__header-wrapper {
      display: none;
    }
  }

</style>
